﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeRepositoryConsole.Algorithm.LeetCode
{
    public class ListNode
    {
        public int val;

        public ListNode next;

        public ListNode(int x) { val = x; }

    }

    public class Solution
    {
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
        {

            var c1 = l1;
            var c2 = l2;

            var sentinel = new ListNode(0);
            var d = sentinel;
            var sum = sentinel.val;

            while (c1 != null || c2 != null)
            {
                sum = sum / 10;

                if (c1 != null)
                {
                    sum += c1.val;
                    c1 = c1.next;
                }

                if (c2 != null)
                {
                    sum += c2.val;
                    c2 = c2.next;
                }

                d.next = new ListNode(sum % 10);
                d = d.next;
            }

            if (sum / 10 == 1)
            {
                d.next = new ListNode(1);
            }

            return sentinel.next;
        }
    }
}
